<template>
	<view class="progress-contanier" ref="containerRef" id="container" @touchstart="handleTouchStart"
		@touchmove="handleTouchMove" @touchend="handleTouchEnd">
		<u-line-progress :percent="progress" activeColor="blue"></u-line-progress>
	</view>

</template>

<script>
	/*
	 * 分装可拖动进度条
	 */
	export default {
		props: {
			defaultProgress: {
				type: Number,
				default: 0,
			},
			// 是否可拖动
			moveable: {
				type: Boolean,
				default: true,
			},
			// 进度是否点击是跳到点击位置
			clickable: {
				type: Boolean,
				default: false,
			}
		},
		data() {
			return {
				width: 300,
				left: 0,
				startX: 0,
				moveX: 0,
				progress: 0
			};
		},
		watch: {
			defaultProgress: {
				handler: function(val) {
					this.progress = val
				},
				immediate: true
			}
		},
		mounted() {
			this.progressDOM = this.$refs.uLineProgressRef
			this.updateContainerWidth()
		},
		methods: {
			handleTouchStart(event) {
				this.startX = event.touches[0].pageX;
				if (this.clickable) this.progress = Math.round((this.startX - this.left) / this.width * 100)
			},
			handleTouchMove(event) {
				this.moveX = event.touches[0].pageX;
				let number = (this.moveX - this.startX) / this.width * 100
				if (this.moveable) this.progress = this.progress + number >= 100 ? 100 : this.progress + number <= 0 ? 0 :
					Math.round((this
						.progress + number))
				this.startX = this.moveX
			},
			updateContainerWidth() {
				// 使用 uni.createSelectorQuery() 获取元素的宽度
				uni.createSelectorQuery().in(this).select('#container').boundingClientRect(data => {
					if (data) {
						this.width = data.width || 300
						this.left = data.left || 0
					}
				}).exec();
			},
			handleTouchEnd() {
				this.$emit('change', this.progress)
			}
		},
	};
</script>

<style>
	.progress-contanier {
		width: 100%;
	}
</style>